'''
@create_time: 2025/10/23 下午4:58
@Author: GeChao
@File: qyapi.py
'''
import requests
import base64
import hashlib
import json



def path2base64(path):
    """
    文件转换为base64
    :param path: 文件路径
    :return:
    """
    with open(path, "rb") as f:
        byte_data = f.read()
    base64_str = base64.b64encode(byte_data).decode("ascii")  # 二进制转base64
    return base64_str


def path2md5(path):
    """
    文件转换为md5
    :param path: 文件路径
    :return:
    """
    with open(path, "rb") as f:
        byte_data = f.read()
    md5_str = md5(byte_data)
    return md5_str


def md5(text):
    """
    md5加密
    :param text:
    :return:
    """
    m = hashlib.md5()
    m.update(text)
    return m.hexdigest()


# 上传文件
def upload_file(file_path, key):
    """
    企业微信机器人上传文件，发送文件前需要现上传
    :param file_path: 文件路径
    :return:
    """

    data = {'file': open(file_path, 'rb')}
    resp = requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={key}&type=file", files=data)
    json_res = resp.json()
    if json_res.get('errcode') == 0:
        print(f"企业微信机器人上传文件成功，file:{file_path}")
        return json_res.get('media_id')
    else:
        print(f"企业微信机器人上传文件失败，file:{file_path}")
        return json.loads(resp.text)


class QY:
    def __init__(self, key):
        self.key = key
        self.url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}"

    # 发送图片
    def image(self, image):
        data = {
            "msgtype": "image",
            "image": {
                "base64": path2base64(image),
                "md5": path2md5(image)
            }}
        resp = requests.post(url=self.url, json=data)
        print(resp.text)
        return json.loads(resp.text)

    # 发送文件
    def send_file(self, file):
        media_id = upload_file(file, self.key)
        data = {
            "msgtype": "file",
            "file": {
                "media_id": media_id
            }
        }
        resp = requests.post(url=self.url, json=data)
        return json.loads(resp.text)

    # 发送文本
    def send_text(self, text):
        data = {
            "msgtype": "text",
            "text": {
                "content": text
            }
        }
        resp = requests.post(url=self.url, json=data)
        return json.loads(resp.text)

    # 发送markdown文本
    def markdown(self, content: str):
        data = {
            "msgtype": "markdown",
            "markdown": {
                "content": content
            }
        }
        resp = requests.post(url=self.url, json=data)
        return json.loads(resp.text)

    # 发送图文类型
    def news(self, news):
        data = {
            "msgtype": "news",
            "news": {
                "articles": [
                    {
                        "title": "中秋节礼品领取",
                        "description": "今年中秋节公司有豪礼相送",
                        "url": "http://172.16.111.123:49788",
                        "picurl": "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png"
                    }
                ]
            }
        }
        resp = requests.post(url=self.url, json=data)
        return json.loads(resp.text)


if __name__ == '__main__':
    # qy.image("C:/Users/Administrator/Pictures/Saved Pictures/1.jpg")
    # 发送文件
    # qy.send_file("main.py")
    # 发送文本
    # qy.send_text("hello world")
    # 发送markown文本
    # qy.markdown({"type": '公有云', 'total': 200, 'success': 20, 'fail': 1, 'skip': 0,
    #              'report_url': 'http://172.16.111.123:49788',
    #              'passed_detail': '>1.核心流程-发货<font color=\"green\">1</font>条通过\n2.核心流程-采购<font color=\"green\">1</font>条通过\n3.核心流程-es<font color=\"green\">1</font>条查询通过\n4.核心流程-订单列表<font color=\"green\">1</font>条查询通过5.wms接口自动化<font color=\"green\">1</font>条通过',
    #              'fail_detail': ''})
    # 发送图文信息
    # qy.news('123132')
    pass
